import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/common/res/gaps.dart';
import 'package:oramemo/common/styles/colors.dart';
import 'package:oramemo/common/utils/extension_util.dart';
import 'package:oramemo/common/utils/time_util.dart';
import 'package:oramemo/generated/assets.dart';
import 'package:oramemo/widgets/audio/audio_player_widget.dart';
import 'package:oramemo/widgets/bookmark_list_bottom_sheet.dart';
import 'package:oramemo/widgets/search_dialog.dart';
import 'package:oramemo/widgets/share_dialog.dart';
import 'package:oramemo/common/langs/text_key.dart';

import 'transcript_item.dart';
import 'transcription_details_logic.dart';

class TranscriptionDetailsPage extends StatelessWidget {
  const TranscriptionDetailsPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: Get.width,
      height: Get.height,
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
          colors: [
            Color(0Xffc4ddf9),
            Color(0Xffcdf3ef),
          ],
        ),
      ),
      child: GetBuilder<TranscriptionDetailsLogic>(
          init: TranscriptionDetailsLogic(),
          builder: (logic) {
            final data = logic.controller.selectedVoiceRecord;
            final title = data?.voicePath?.split('/').last ?? '';
            return Scaffold(
              backgroundColor: Colors.transparent,
              appBar: PreferredSize(
                preferredSize: Size(Get.width, Get.statusBarHeight),
                child: SafeArea(
                  child: Padding(
                    padding: const EdgeInsets.fromLTRB(16, 8, 16, 8.0),
                    child: Row(
                      children: [
                        InkWell(
                            onTap: () => Get.back(),
                            child: const Icon(Icons.arrow_back_ios,
                                color: Colours.text)),
                        Text(
                          '00:00/${TimeUtils.formatDuration(Duration(seconds: data?.voiceDuration ?? 0))}',
                          style: const TextStyle(
                              fontSize: 16, color: Colours.text),
                        ),
                        const Spacer(),
                        _buildInkWell(Assets.transcriptionDetailsSearch,
                            onTap: () {
                          showDialog(
                            context: context,
                            builder: (context) => SearchDialog(
                              segments:
                                  logic.transliterateEntity.segments ?? [],
                              onItemSelected: (segment) {
                                logic.setForward(segment);
                                logic.scrollToSegment(segment);
                              },
                            ),
                          );
                        }),
                        // 修改转换按钮的点击事件
                        _buildInkWell(
                          Assets.transcriptionDetailsConvert,
                          onTap: () {
                            showDialog(
                              context: context,
                              builder: (context) => Dialog(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Container(
                                  padding: const EdgeInsets.all(24),
                                  child: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      const SizedBox(height: 16),
                                      // AI总结文字
                                      Text(
                                        TextKey.transcriptionDetailsConvert.tr,
                                        style: const TextStyle(
                                          fontSize: 20,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      Gaps.vGap24,
                                      // AI总结文字
                                      Text(
                                        data?.voiceContent ?? '',
                                        style: const TextStyle(
                                          fontSize: 16,
                                        ),
                                      ),
                                      const SizedBox(height: 24),
                                      // 关闭按钮
                                      TextButton(
                                        onPressed: () => Navigator.pop(context),
                                        child: Text(TextKey
                                            .transcriptionDetailsClose.tr),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                        _buildInkWell(Assets.transcriptionDetailsShare,
                            onTap: () {
                          final segments =
                              logic.transliterateEntity.segments ?? [];
                          final transcripts =
                              segments.map((e) => e.text ?? '').toList();
                          final audioUrl = logic
                                  .controller.selectedVoiceRecord?.voicePath
                                  ?.toFullUrl() ??
                              '';
                          final title = logic
                                  .controller.selectedVoiceRecord?.voicePath
                                  ?.split('/')
                                  .last ??
                              '';

                          showDialog(
                            context: context,
                            builder: (context) => ShareDialog(
                              title: title,
                              audioUrl: audioUrl,
                              transcripts: transcripts,
                            ),
                          );
                        }),
                      ],
                    ),
                  ),
                ),
              ),
              body: SafeArea(
                child: Container(
                  color: const Color(0xffF3F6F9),
                  child: Column(
                    children: [
                      if (logic.isPlayer)
                        AudioPlayerWidget(
                          audioUrl: data?.voicePath?.toFullUrl() ?? '',
                          controller: logic.audioPlayerController,
                        )
                      else
                        // Title
                        Container(
                          padding: const EdgeInsets.all(16),
                          child: Row(
                            children: [
                              Container(
                                width: 5,
                                height: 5,
                                decoration: const BoxDecoration(
                                  color: Colors.blue,
                                  shape: BoxShape.circle,
                                ),
                              ),
                              const SizedBox(width: 8),
                              Expanded(
                                child: Text(
                                  title,
                                  maxLines: 2,
                                  style: const TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.w500),
                                ),
                              ),
                            ],
                          ),
                        ),

                      // Metadata
                      Expanded(
                        child: Container(
                          margin: const EdgeInsets.only(
                              left: 16, right: 16, top: 2),
                          decoration: const BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(16),
                              topRight: Radius.circular(16),
                            ),
                          ),
                          child: Column(
                            children: [
                              if (!logic.isPlayer)
                                Container(
                                  padding:
                                      const EdgeInsets.fromLTRB(10, 12, 10, 12),
                                  child: Row(
                                    children: [
                                      const Icon(CupertinoIcons.calendar,
                                          size: 16, color: Colors.grey),
                                      const SizedBox(width: 4),
                                      Text(
                                          TimeUtils.formatDateStr(
                                              data?.createTime ?? ''),
                                          style: const TextStyle(
                                              color: Colors.grey)),
                                      const SizedBox(width: 16),
                                      const Icon(CupertinoIcons.time,
                                          size: 16, color: Colors.grey),
                                      const SizedBox(width: 4),
                                      Text(
                                          TimeUtils.formatDuration(Duration(
                                              seconds:
                                                  data?.voiceDuration ?? 0)),
                                          style: const TextStyle(
                                              color: Colors.grey)),
                                    ],
                                  ),
                                ),

                              // Transcript
                              Expanded(
                                child: ListView.builder(
                                  controller: logic.scrollController,
                                  padding: const EdgeInsets.all(16),
                                  itemCount: logic.transliterateEntity.segments
                                          ?.length ??
                                      0,
                                  itemBuilder: (context, index) {
                                    final item = logic
                                        .transliterateEntity.segments![index];
                                    return TranscriptItem(
                                      key: ValueKey(item.id),
                                      time: _formatDuration(item.start!),
                                      text: item.text ?? "",
                                      isSelected:
                                          logic.selectSegment?.id == item.id,
                                      isBookmarked: logic.isBookmarked(
                                          item.id?.toString() ?? ''),
                                      onTap: () {
                                        logic.setForward(item);
                                      },
                                    );
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),

                      // Bottom Controls
                    ],
                  ),
                ),
              ),
              bottomNavigationBar: Container(
                padding: const EdgeInsets.fromLTRB(10, 5, 10, 15),
                decoration: const BoxDecoration(
                  color: Colors.white,
                  border: Border(
                    top: BorderSide(color: Colors.black12),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildLikeButton(
                        imgPath: Assets.transcriptionDetailsStamp,
                        isLiked: logic.isCurrentBookmarked, // 使用当前选中段落的书签状态
                        onTap: () {
                          logic.toggleBookmark();
                        }),
                    // _buildInkWell(Assets.transcriptionDetailsSpeed, onTap: () {}),
                    _buildLikeButton(
                        imgPath: Assets.transcriptionDetailsLive,
                        isLiked: logic.isLiked,
                        onTap: () {
                          logic.toggleLike();
                        }),
                    _buildLikeButton(
                        imgPath: Assets.transcriptionDetailsPlay,
                        isLiked: logic.isPlayer,
                        onTap: () {
                          logic.isPlayer = !logic.isPlayer;
                          logic.update();
                        }),
                    _buildInkWell(
                      Assets.transcriptionDetailsDirectory,
                      onTap: () {
                        showModalBottomSheet(
                          context: context,
                          backgroundColor: Colors.transparent,
                          isScrollControlled: true,
                          builder: (context) => BookmarkListBottomSheet(
                            bookmarks: logic.getBookmarkedSegments(),
                            onTap: (segment) {
                              logic.setForward(segment);
                              logic.scrollToSegment(segment);
                            },
                            onDelete: (segment) {
                              logic.removeBookmark(segment.id.toString());
                            },
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ),
            );
          }),
    );
  }

  InkWell _buildInkWell(String imgPath, {Function()? onTap}) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.all(7.0),
        child: IconX.image(imgPath, size: 26),
      ),
    );
  }

  // 格式化时间
  String _formatDuration(String duration) {
    final start = (duration.toDouble() ?? 0) * 1000;
    return TimeUtils.formatDuration(Duration(milliseconds: start.toInt()));
  }

  // 在 _TranscriptItem 中添加动画效果
  Widget _buildLikeButton(
      {required String imgPath, bool isLiked = false, Function()? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        child: TweenAnimationBuilder(
          tween: Tween<double>(begin: 1.0, end: isLiked ? 1.2 : 1.0),
          duration: const Duration(milliseconds: 200),
          builder: (context, double value, child) {
            return Transform.scale(
              scale: value,
              child: IconX.image(
                imgPath,
                size: 26,
                color: isLiked ? Colors.blue : Colors.grey,
              ),
            );
          },
        ),
      ),
    );
  }
}
